package com.japstudy.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.japstudy.entity.Word;
import com.japstudy.entity.WrongWord;
import com.japstudy.service.IWordService;
import com.japstudy.service.IWrongWordService;

@Controller
@RequestMapping("/WrongWord")
public class WrongWordController {

	@Autowired
	private IWrongWordService wrongWordServiceImpl;
	@Autowired
	private IWordService wordServiceImpl;
	
	@RequestMapping("/selectWrongWordOfTopTen")
	public @ResponseBody List<WrongWord> selectWrongWordOfTopTen(String userId){
		List<WrongWord> wrongWords = wrongWordServiceImpl.selectWrongWordOfTopTen(userId);
		List<WrongWord> wrongWordOfTopTen = new ArrayList<WrongWord>();
		for (int i = 0; i < 20 && i <wrongWords.size(); i++) {
			wrongWordOfTopTen.add(wrongWords.get(i));
		}
		if(wrongWordOfTopTen != null && wrongWordOfTopTen.size() > 0) {
			for (WrongWord wrongWord : wrongWordOfTopTen) {
				String wordId = wrongWord.getWord().getWordId();
				Word word = wordServiceImpl.selectById(wordId);
				wrongWord.setWord(word);
			}
		}
		return wrongWordOfTopTen;
	}
	
	@RequestMapping("/updateMaster")
	public String updateMaster(HttpServletResponse response, HttpServletRequest request, WrongWord wrongWord) throws IOException{
		wrongWord.setMaster(1);
		String userId = wrongWord.getUser().getUserId();
		wrongWordServiceImpl.updateMaster(wrongWord);
		response.sendRedirect(request.getContextPath() + "/Word/userSelectAllWrongWord?userId=" + userId);
		return null;
	}
}
